package com.module.aichat.db

import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.common.base.utils.AppUtils
import com.module.aichat.db.converter.ContentConverter
import com.module.aichat.db.table.DBMessage

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2025/6/30
 * <p>
 * 描述：room数据库
 * <p>
 * 修订历史：
 */
@Database(
    entities = [DBMessage::class,],
    version = 2
)//添表升级
@TypeConverters(ContentConverter::class)
abstract class ChatAppDataBase : RoomDatabase() {

    companion object {
        private var mChatDataBase: ChatAppDataBase? = null
        private var mCurrentUserId: String = ""

        fun getDb(userId: String): ChatAppDataBase? {
            // 第一次登录或切换用户，创建数据库实例
            // 如果先前有用户登录，则关闭之前用户的数据库实例
            if (mCurrentUserId != userId || mChatDataBase == null) {
                mCurrentUserId = userId
                mChatDataBase?.close()
                mChatDataBase = buildDatabase(userId)
            }
            return mChatDataBase
        }

        private fun buildDatabase(userId: String): ChatAppDataBase {
            return Room.databaseBuilder(
                AppUtils.getContext(), ChatAppDataBase::class.java, "gh_ai_chat_$userId.db"
            )
                .allowMainThreadQueries()
                .addMigrations(MIGRATION_1_2)
                .build()
        }


        private val MIGRATION_1_2 = object : Migration(1, 2) {
            //数据表添加字段
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE chat_message ADD COLUMN likeStatus INTEGER NOT NULL DEFAULT 0")
                database.execSQL("ALTER TABLE chat_message ADD COLUMN fallStatus INTEGER NOT NULL DEFAULT 0")
            }
        }
    }

    abstract fun getChatMessageDao(): ChatMessageDao
}
